import { h } from 'vue'
import type { DataTableColumns } from 'naive-ui/es'
import type { DownloadApiFunction } from '@/hooks/useDownload'

/**
 * * @description 生成Excel兼容的CSV内容
 * ! @return CSV格式的字符串
 */
export const generateExcelCSV = (): string => {
  const headers = ['序号', '姓名', '邮箱', '部门', '入职日期', '薪资']
  const data = [
    ['1', '张三', 'zhangsan@example.com', '技术部', '2023-01-15', '15000'],
    ['2', '李四', 'lisi@example.com', '市场部', '2023-02-20', '12000'],
    ['3', '王五', 'wangwu@example.com', '人事部', '2023-03-10', '10000'],
    ['4', '赵六', 'zhaoliu@example.com', '财务部', '2023-04-05', '13000'],
    ['5', '刘七', 'liuqi@example.com', '技术部', '2023-05-12', '16000'],
  ]
  return [headers, ...data].map(row => row.join(',')).join('\n')
}

/**
 * * @description 生成简单的PDF内容（英文避免乱码）
 * ? @param title - PDF标题
 * ? @param content - PDF内容描述
 * ! @return PDF格式的字符串
 */
export const generateSimplePDF = (title: string, content: string): string => {
  console.log('🚀 ~ generateSimplePDF ~ content:', content)
  const englishTitle = 'Demo Document'
  const englishContent =
    'This is a sample PDF document generated by the download demo.'
  const timestamp = new Date().toISOString()

  return `%PDF-1.4
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj

2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj

3 0 obj
<<
/Type /Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 4 0 R
/Resources <<
/Font <<
/F1 5 0 R
>>
>>
>>
endobj

4 0 obj
<<
/Length 150
>>
stream
BT
/F1 16 Tf
50 750 Td
(${englishTitle}) Tj
0 -30 Td
/F1 12 Tf
(${englishContent}) Tj
0 -20 Td
(Generated: ${timestamp}) Tj
0 -20 Td
(File: ${title}) Tj
ET
endstream
endobj

5 0 obj
<<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
>>
endobj

xref
0 6
0000000000 65535 f 
0000000009 00000 n 
0000000058 00000 n 
0000000115 00000 n 
0000000274 00000 n 
0000000476 00000 n 
trailer
<<
/Size 6
/Root 1 0 R
>>
starter
565
%%EOF`
}

/**
 * * @description 内容生成器配置
 */
export const contentGenerators = {
  excel: () => ({
    content: generateExcelCSV(),
    mimeType:
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  }),
  csv: () => ({
    content: generateExcelCSV(),
    mimeType: 'text/csv',
  }),
  json: (params: Record<string, unknown>) => ({
    content: JSON.stringify(
      {
        code: 200,
        message: 'Success',
        data: [
          {
            id: 1,
            name: 'Sample Data',
            type: 'demo',
            createTime: new Date().toISOString(),
          },
          {
            id: 2,
            name: 'Test Data',
            type: 'test',
            createTime: new Date().toISOString(),
          },
        ],
        meta: { total: 2, params, exportTime: new Date().toISOString() },
      },
      null,
      2
    ),
    mimeType: 'application/json',
  }),
  pdf: () => ({
    content: generateSimplePDF('Demo Document', 'Sample content'),
    mimeType: 'application/pdf',
  }),
  users: () => ({
    content: generateExcelCSV(),
    mimeType:
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  }),
  orders: () => ({
    content:
      'Order ID,Customer,Product,Quantity,Amount,Date\nORD001,John Doe,Product A,2,299.00,2024-01-15\nORD002,Jane Smith,Product B,1,599.00,2024-01-16',
    mimeType: 'text/csv',
  }),
  products: () => ({
    content: generateSimplePDF('Product List', 'Product catalog'),
    mimeType: 'application/pdf',
  }),
  logs: (params: Record<string, unknown>) => ({
    content: `System Log File\nGenerated: ${new Date().toISOString()}\nParameters: ${JSON.stringify(params)}\n\n[INFO] 2024-01-15 10:00:00 - System started successfully\n[INFO] 2024-01-15 10:01:00 - User login: admin\n[WARN] 2024-01-15 10:02:00 - Memory usage reached 80%\n[INFO] 2024-01-15 10:03:00 - Data backup completed`,
    mimeType: 'text/plain',
  }),
  config: (params: Record<string, unknown>) => ({
    content: JSON.stringify(
      {
        app: {
          name: 'Robot Admin',
          version: '1.0.0',
          environment: 'production',
        },
        database: { host: 'localhost', port: 3306, name: 'robot_admin' },
        features: { download: true, upload: true, export: true },
        exportTime: new Date().toISOString(),
        params,
      },
      null,
      2
    ),
    mimeType: 'application/json',
  }),
}

/**
 * * @description 创建模拟API函数
 * ? @param fileType - 文件类型
 * ! @return 下载API函数
 */
export const createMockApi = (fileType: string): DownloadApiFunction => {
  return async (params = {}) => {
    await new Promise(resolve =>
      setTimeout(resolve, 1000 + Math.random() * 2000)
    )

    const generator =
      contentGenerators[fileType as keyof typeof contentGenerators]
    const { content, mimeType } = generator
      ? generator(params)
      : {
          content: `File Type: ${fileType}\nGenerated: ${new Date().toISOString()}\nParameters: ${JSON.stringify(params, null, 2)}`,
          mimeType: 'text/plain',
        }

    return new Blob([content], { type: mimeType })
  }
}

/**
 * * @description 批量下载文件配置
 */
export const batchFiles = [
  { key: 'users', label: '用户数据报表.xlsx' },
  { key: 'orders', label: '订单统计.csv' },
  { key: 'products', label: '商品清单.pdf' },
  { key: 'logs', label: '系统日志.txt' },
  { key: 'config', label: '配置信息.json' },
]

/**
 * * @description 历史表格列配置
 */
export const historyColumns: DataTableColumns = [
  { title: '文件名', key: 'fileName' },
  { title: '类型', key: 'fileType' },
  {
    title: '状态',
    key: 'status',
    render: (row: any) => {
      const statusMap = {
        success: { text: '成功', color: '#18a058' },
        failed: { text: '失败', color: '#d03050' },
        pending: { text: '进行中', color: '#f0a020' },
      }
      const status = statusMap[row.status as keyof typeof statusMap]
      return h('span', { style: { color: status.color } }, status.text)
    },
  },
  { title: '下载时间', key: 'downloadTime' },
]

/**
 * * @description 下载历史数据项类型
 */
export interface HistoryItem {
  id: string
  fileName: string
  fileType: string
  status: 'success' | 'failed' | 'pending'
  downloadTime: string
}
